<?php
/**
 * @author spenceryg
 * @date 2023/3/18
 * @time 9:36 上午
 * @focus love & life
 */


namespace app\api\business;



use app\common\lib\verify\interfaces\Verify;
use app\common\lib\verify\VerifyFactory;
use app\common\model\Member;
use Exception;
use think\facade\App;
use think\facade\Db;
use think\facade\Event;
use think\Request;

class CommonBusiness
{
    /**
     * sendVerifyCode
     * @param string $to
     * @param Verify $type
     * @param int $length
     * @param string $code
     * @throws Exception
     */
    public function sendVerifyCode(string $to,Verify $type,int $length = 0,string $code = '')
    {
        try{
            $factory = new VerifyFactory($type);
            $factory->setTo($to)->setCode($length?: 4, $code)->send();
        }catch (Exception $e){
            throw new Exception($e->getMessage());
        }
    }


    /**
     * isMemberExist
     * @param $to
     * @param $type
     * @throws Exception
     */
    public function isMemberExist($to, $type)
    {
        $field = 'phone';
        $field_name = '手机号码';
        if ($type === 'EmailVerify') {
            $field = 'email';
            $field_name = '电子邮箱';
        }
        try {
            $find = Member::where($field, $to)->find();
            if (!$find) {
                throw new Exception($field_name. ':' . $to . '未注册！');
            }
        } catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
    }

    /**
     * isMemberNotExist
     * @param $to
     * @param $type
     * @throws Exception
     */
    public function isMemberNotExist($to, $type)
    {
        $field = 'phone';
        $field_name = '手机号码';
        if ($type === 'EmailVerify') {
            $field = 'email';
            $field_name = '电子邮箱';
        }
        try {
            $find = Member::where($field, $to)->find();
            if ($find) {
                throw new Exception($field_name. ':' . $to . '已存在！');
            }
        } catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 注册
     * register
     * @param array $data
     * @throws Exception
     */
    public function register(array $data)
    {
        try{
            validate(MemberValidate::class)->scene('register')->check($data);
            Db::startTrans();
            $member = Member::create($data);
            $member->name = 'ddi_' . $member->id;
            $member->save();
            $res = Event::trigger('MemberRegister', [App::getInstance()->make(Request::class),$member->id]);
            if (!$res){
                throw new Exception('内部错误！请联系管理员！');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 注册
     * register
     * @param array $data
     * @throws Exception
     */
    public function register1(array $data)
    {
        try{
            validate(MemberValidate::class)->scene('register1')->check($data);
            $data['is_doctor'] = 1;
            Db::startTrans();
            $member = Member::create($data);
            $member->name = 'xhs_' . $member->id;
            $member->save();
            $res = Event::trigger('MemberRegister', [App::getInstance()->make(Request::class),$member->id]);
            if (!$res){
                throw new Exception('内部错误！请联系管理员！');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * registerBind
     * @param array $data
     * @throws Exception
     */
    public function registerBind(array $data)
    {
        try{
            validate(MemberValidate::class)->scene('bind')->check($data);
            Db::startTrans();
            $member = Member::where('phone', $data['phone'])->find();
            if ($member){
                $member->union_id = $data['union_id'];
                $member->save();
            } else {
                $member = Member::create($data);
                $member->name = 'ddi_' . $member->id;
                $member->save();
            }
            $res = Event::trigger('MemberRegister', [App::getInstance()->make(Request::class),$member->id]);
            if (!$res){
                throw new Exception('内部错误！请联系管理员！');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }


    /**
     * registerBind
     * @param array $data
     * @throws Exception
     */
    public function registerBind1(array $data)
    {
        try{
            validate(MemberValidate::class)->scene('bind1')->check($data);
            Db::startTrans();
            $member = Member::where('phone', $data['phone'])->find();
            if ($member){
                $member->union_id = $data['union_id'];
                $member->save();
            } else {
                $member = Member::create($data);
            }
            $res = Event::trigger('MemberRegister', [App::getInstance()->make(Request::class),$member->id]);
            if (!$res){
                throw new Exception('内部错误！请联系管理员！');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * login
     * @param array $data
     * @throws Exception
     */
    public function login(array $data)
    {
        try {
            validate(LoginValidate::class)->scene(str_replace('_', '', $data['scene']))->check($data);
            Db::startTrans();
            $member = Member::where('phone', $data['to'])->find();
            if(!$member){
                $member = Member::create($data);
                $member->phone = $data['to'];
                $member->name = 'ddi_' . $member->id;
                $member->save();
                $res = Event::trigger('MemberRegister', [App::getInstance()->make(Request::class),$member->id]);
                if (!$res){
                    throw new Exception('内部错误！请联系管理员！');
                }
            }
//            if(!$member['is_normal']){
//                throw new Exception('该账号已被禁用！禁止登录！');
//            }
            $res = Event::trigger('MemberLogin', [App::getInstance()->make(Request::class),$member->id]);
            if (!$res){
                throw new Exception('内部错误！请联系管理员！');
            }
            Db::commit();
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 密码加密
     * getPassword
     * @param string $password
     * @return string
     */
    public static function getPassword(string $password): string
    {
        return md5($password . 'spencer');
    }

    /**
     * 验证账号密码
     * passwordRight
     * @param string $to
     * @param string $password
     * @param string $filed
     * @throws Exception
     */
    public static function passwordRight(string $to, string $password, string $filed = 'name|phone')
    {
        try {
            $member = Member::where($filed, $to)->find();
            if (!$member){
                throw new Exception('账号不存在！');
            }
            $now_password = $member['password'];
            $password = self::getPassword($password);
            if ($now_password != $password) {
                throw new Exception('密码错误！');
            }

        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }


    /**
     * changePassword
     * @param array $data
     * @throws Exception
     */
    public function changePassword(array $data)
    {
        try {
            validate(ForgetValidate::class)->scene('forget2')->check($data);
            $password = self::getPassword($data['password']);
            $phone = session('can_change_password');
            Member::where('phone', $phone)->save(['password' => $password]);
            session('can_change_password', null);
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

}
